package com.zhanghe.wzq.handler.request;

import com.zhanghe.wzq.ChessStep;
import com.zhanghe.wzq.Table;
import com.zhanghe.wzq.User;
import com.zhanghe.wzq.command.request.OneStepRequest;
import com.zhanghe.wzq.command.response.OneStepResponse;
import com.zhanghe.wzq.data.Attributes;
import com.zhanghe.wzq.data.TableManager;
import com.zhanghe.wzq.data.UserChannelManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * OneStepRequestHandler
 *
 * @author Clevo
 * @date 2019/1/12
 */
public class OneStepRequestHandler extends SimpleChannelInboundHandler<OneStepRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, OneStepRequest oneStepRequest) throws Exception {
        User current = channelHandlerContext.channel().attr(Attributes.USER).get();
        Table table = TableManager.INSTANCE.getUserTable(current.getId());
        ChessStep step = table.getGame().addStep(oneStepRequest.getX(),oneStepRequest.getY(),current.getId());
        OneStepResponse oneStepResponse = new OneStepResponse();
        if(step!=null){
            if(step.isSucces()){
                System.out.println();
                oneStepResponse.setX(step.getX());
                oneStepResponse.setY(step.getY());
                oneStepResponse.setColor(step.getValue());
                oneStepResponse.setWinner(current.getId());
                oneStepResponse.setSuccess(true);

                channelHandlerContext.writeAndFlush(oneStepResponse);

                String anotherUserId = table.getGame().getAnotherUser(current.getId());
                OneStepResponse another = new OneStepResponse();
                another.setX(step.getX());
                another.setY(step.getY());
                another.setColor(step.getValue());
                another.setWinner(current.getId());
                another.setSuccess(true);
                UserChannelManager.getInstance().getUserChannel(anotherUserId).writeAndFlush(another);
            }else{
                oneStepResponse.setX(step.getX());
                oneStepResponse.setY(step.getY());
                oneStepResponse.setColor(step.getValue());
                oneStepResponse.setSuccess(true);

                channelHandlerContext.writeAndFlush(oneStepResponse);

                String anotherUserId = table.getGame().getAnotherUser(current.getId());
                OneStepResponse another = new OneStepResponse();
                another.setX(step.getX());
                another.setY(step.getY());
                another.setColor(step.getValue());
                another.setSuccess(true);
                UserChannelManager.getInstance().getUserChannel(anotherUserId).writeAndFlush(another);
            }
        }
    }
}
